#!/usr/bin/python2.7
# -*- coding: utf-8 -*-

import time
import os
import shutil
import subprocess


popendict = dict()
currentseed_prepare = set()



work_dir = "/data/qinz18/STAR/LLfit_ccode"
seed_cmd = "root -b -q -l LL_cpp.C\(SEED\)"

# https://www.runoob.com/python/python-os-path.html
# https://docs.python.org/zh-cn/3/library/shutil.html

# ///// scale5 <<<
nbin_f0=25
nbin_d0=25
nbin_R=25
N_seed  = nbin_f0*nbin_d0*nbin_R
#    ///// scale5 >>>


N_Core = 40

currentseed_prepare.update(range(0,N_seed))



  

def makepath(p):
  if not os.path.exists(p):       # 判断文件夹是否存在
    #shutil.rmtree(p)        # 删除文件夹
    #os.mkdir(p)                 # 创建文件夹
    os.makedirs(p)                 # 创建多级文件夹




os.chdir(work_dir)
print("current dir = ",os.getcwd())


f_log = open("./LL_MT.log", "a")

while True:
  for seed in list(popendict.keys()):
    state = popendict[seed].poll()
    if state == 0:
      print("seed done:",seed)
      f_log.write("seed done:"+str(seed)+"\n")
      f_log.write(str(popendict[seed].communicate())+"\n")
      # delete popen in popendict
      del popendict[seed]
    elif state == None:
      donothing = 1
      # f_log.write("filename="+filename+" popendict[filename].poll() = "+str(state)+"\n")
      # TODO::If send one file too long,something wrong with rsync, kill this popen: popendict[filename].kill() or popendict[filename].send_signal(15)
    else:
      f_log.write("seed="+seed+" popendict[seed].poll() = "+str(state)+"\n")
      del popendict[seed]
      #(stdoutput,erroutput) = popendict[seed].communicate()
      #f_log.write(str(popendict[seed].communicate())+"\n")
      #f_log.write("stdoutput="+stdoutput+"\n"+"erroutput"+erroutput)
      # TODO::If send one file too long,something wrong with rsync, kill this popen: popendict[seed].kill() or popendict[filename].send_signal(15)
  # add new popens to popendict
  # while len(popendict)<100 and len(currentseed_prepare)>0:
  # while len(popendict)<20 and len(currentseed_prepare)>0:
  # while len(popendict)<50 and len(currentseed_prepare)>0:
  while len(popendict)<N_Core and len(currentseed_prepare)>0:
    if len(popendict)>1: print("len(popendict)=",len(popendict))
    print("len(currentseed_prepare)=",len(currentseed_prepare))
    seed = currentseed_prepare.pop()
    popen = subprocess.Popen(seed_cmd.replace("SEED",str(seed)),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    popendict[seed]=popen
  time.sleep(0.1)

# f_log.close()

